package com.example.yiparkapplication.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSONObject;
import com.example.yiparkapplication.MainActivity;
import com.example.yiparkapplication.constant.API;
import com.example.yiparkapplication.constant.Constant;
import com.example.yiparkapplication.entity.UserRegistrationInformation;
import com.example.yiparkapplication.tool.IdentifyingCode;
import com.example.yiparkapplication.util.Common;
import com.example.yiparkapplication.util.MD5Utils;
import com.example.yiparkapplication.util.ProgressDialogUtil;
import com.rey.material.widget.Button;

import com.example.yiparkapplication.R;
import com.example.yiparkapplication.util.BaseActivity;
import com.rey.material.widget.CheckBox;
import com.rey.material.widget.EditText;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends BaseActivity {

    private CheckBox vCheckBox;
    private UserRegistrationInformation mUserRegistrationInformation = new UserRegistrationInformation();
    private AlertDialog progressDialog;
    private ImageView identifyingCode;
    private String realCode;
    private Button phoneCodeButton;
    private Timer timer;
    private int mClick = 60;
    private String mSessionId = null;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_layout);
        Button registerButton = (Button) findViewById(R.id.id_register);
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!vCheckBox.isChecked()){
                    Toast.makeText(RegisterActivity.this, "未勾选同意条款", Toast.LENGTH_LONG).show();
                    return;
                }
                checkEditTexts();
            }
        });
        identifyingCode = (ImageView) findViewById(R.id.id_get_img_code);
        identifyingCode.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                identifyingCode.setImageBitmap(IdentifyingCode.getInstance().createBitmap());
                realCode = IdentifyingCode.getInstance().getCode().toLowerCase();
            }
        });
        identifyingCode.setImageBitmap(IdentifyingCode.getInstance().createBitmap());
        realCode = IdentifyingCode.getInstance().getCode();

        phoneCodeButton = (Button) findViewById(R.id.id_get_phone_code);
        phoneCodeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mClick > 0 && mClick < 60){
                    return;
                }
                EditText mPhone = (EditText) findViewById(R.id.id_register_phone);
                String phone = mPhone.getText().toString().trim();
                if ("".equals(mPhone)){
                    Toast.makeText(RegisterActivity.this, Constant.ON_PHONE, Toast.LENGTH_LONG).show();
                    return;
                }
                if (mPhone.length() != 11){
                    Toast.makeText(RegisterActivity.this, Constant.ERROR_PHONE, Toast.LENGTH_LONG).show();
                    return;
                }
                EditText mCheckCode = (EditText) findViewById(R.id.id_check_img_code);
                String checkCode = mCheckCode.getText().toString().trim();
                if ("".equals(checkCode)){
                    Toast.makeText(RegisterActivity.this, "验证码不能为空", Toast.LENGTH_LONG).show();
                    return;
                }
                if (!checkCode.toLowerCase().equals(realCode)){
                    Toast.makeText(RegisterActivity.this, "验证码不正确", Toast.LENGTH_LONG).show();
                    return;
                }
                if (timer != null){
                    myTimerTask mTimerTask = new myTimerTask();
                    timer.schedule(mTimerTask, 0, 1000);
                }else{
                    timer = new Timer();
                    mClick = 60;
                    myTimerTask mTimerTask = new myTimerTask();
                    timer.schedule(mTimerTask, 0, 1000);
                }
                getPhoneCode(phone);
            }
        });

        timer = new Timer();
    }

    private void checkEditTexts(){
        EditText mPhone = (EditText) findViewById(R.id.id_register_phone);
        String phone = mPhone.getText().toString().trim();

        EditText mPassword = (EditText) findViewById(R.id.id_register_password);
        String password = mPassword.getText().toString().trim();
        if ("".equals(password)){
            Toast.makeText(RegisterActivity.this, Constant.ON_PASSWORD, Toast.LENGTH_LONG).show();
            return;
        }
        if (password.length() < 6 || password.length() > 11){
            Toast.makeText(RegisterActivity.this, Constant.ERROR_PASSWROD, Toast.LENGTH_LONG).show();
        }
        EditText mCheckPassword = (EditText) findViewById(R.id.id_check_password);
        String checkPassword = mCheckPassword.getText().toString().trim();
        if ("".equals(checkPassword)){
            Toast.makeText(RegisterActivity.this, "确认密码不能为空", Toast.LENGTH_LONG).show();
            return;
        }
        if (!checkPassword.equals(password)){
            Toast.makeText(RegisterActivity.this, "密码不一致", Toast.LENGTH_LONG).show();
            return;
        }
        EditText mCheckPhoneCode = (EditText) findViewById(R.id.id_check_phone_code);
        String checkPhoneCode = mCheckPhoneCode.getText().toString().trim();
        if ("".equals(checkPhoneCode)){
            Toast.makeText(RegisterActivity.this, Constant.ON_PHONE_VERIFICATION, Toast.LENGTH_LONG).show();
            return;
        }
        mUserRegistrationInformation.setCode(checkPhoneCode);
        mUserRegistrationInformation.setPhoneNumber(phone);
        mUserRegistrationInformation.setPassword(MD5Utils.md5Password(password));
        mUserRegistrationInformation.setType("1");
        toRegister();
    }

    private void toRegister(){
        progressDialog = ProgressDialogUtil.returnProgressDialog(RegisterActivity.this);
        progressDialog.show();

        String json = JSONObject.toJSONString(mUserRegistrationInformation);
        Log.d("object to json", "toRegister: " + json);
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json;charset=utf-8"), json);
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_REGISTER)
                .post(requestBody)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e){
                progressDialog.dismiss();
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response)throws IOException{
                progressDialog.dismiss();
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                Log.d("register", "onResponse: " + joOut.toString());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
                    startActivity(intent);
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_LONG).show();
                    Looper.loop();
                }else{
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), joOut.getString("msg"), Toast.LENGTH_LONG).show();
                    Looper.loop();
                }
            }
        });
    }

    private void getPhoneCode(String phone){
        progressDialog = ProgressDialogUtil.returnProgressDialog(RegisterActivity.this);
        progressDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(API.HOST + API.URL_GET_CODE + "?phoneNumber=" + phone + "&type=" + 0)
                .get()
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                progressDialog.dismiss();
                Common.failureMessage(e.getMessage(), getApplicationContext());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                progressDialog.dismiss();
                String tempResponse = response.body().string();
                JSONObject joOut = Common.tempResponseException(tempResponse, getApplicationContext());
                int code = joOut.getIntValue("code");
                if (code == 100){
                    JSONObject joIn = joOut.getJSONObject("object");
                    mSessionId = joIn.getString("sessionId");
                    mUserRegistrationInformation.setSessionId(mSessionId);
                }else{
                    Looper.prepare();
                    Toast.makeText(RegisterActivity.this, joOut.getString("msg"), Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }
            }
        });
    }

    class myTimerTask extends TimerTask{
        Activity mActivity = new Activity();

        @Override
        public void run(){
            mActivity.runOnUiThread(new Runnable(){
                @Override
                public void run(){
                    mClick--;
                    phoneCodeButton.setText(String.valueOf(mClick));
                    if (mClick == 0){
                        timer.cancel();
                        timer = null;
                        phoneCodeButton.setText(R.string.get_phone_code);
                    }
                }
            });
        }
    }

}
